package com.liaoyin.travel.service.attendance;

import com.github.pagehelper.PageHelper;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.attendance.PunchInRecordMapper;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.attendance.AttendanceSettings;
import com.liaoyin.travel.entity.attendance.PunchInRecord;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.util.DateUtil;
import com.liaoyin.travel.util.LocationUtils;
import com.liaoyin.travel.util.ParamUtil;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.UUIDUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：打卡记录
 * @日期：Created in 2018/6/20 14:55
 */
@Service
public class PunchInRecordService extends BaseService<PunchInRecordMapper, PunchInRecord> {
   
	private Logger log = LoggerFactory.getLogger(PunchInRecordService.class);

	
	@Autowired
	private AttendanceSettingsService attendanceSettingsService;
	@Autowired
	private AttendanceStatisticsService attendanceStatisticsService;
	@Autowired
	private UsersService usersService;
	
	/***
	 * 
	     * @方法名：selectPunchInRecordListToday
	     * @描述： 获取用户当日打卡的记录【每个班次打卡，以最早的一次记录为准】
	     * @作者： lijing
	     * @日期： 2019年7月11日
	 */
	public List<PunchInRecord> selectPunchInRecordListToday(String userId,String time){
		
		List<PunchInRecord> list= this.mapper.selectPunchInRecordListToday(userId,time);
		return list;
	}
	
	
	/*****
	 * 
	     * @方法名：judgeCheckInIsAllowed
	     * @描述： 判断当前员工是否在允许的签到时间及范围
	     * @作者： lijing
	     * @日期： 2019年7月11日
	 */
	public Map<String, Object> judgeCheckInIsAllowed(String lat,String log,String checkShifts,UserInfo user){

		Map<String, Object> map = new HashMap<>();
		if(user==null) {
			UserInfo userInfo = PartyUtil.getCurrentUserInfo();
			if(userInfo == null) {
				throw new BusinessException("not.login");
			}
			user = userInfo;
		}
		
		AttendanceSettings att = null;
		//判断打卡班次
		String isDailyAttendanceCardOpened = ParamUtil.getValue("isDailyAttendanceCardOpened");
		/*if(isDailyAttendanceCardOpened !=null && "1".equals(isDailyAttendanceCardOpened)) {
			//开启班组打卡模式
			if(user.getTeamId()!=null && !"".equals(user.getTeamId())) {
				att = this.attendanceSettingsService.selectAttendanceSettingsByCheckShiftsAndTeamId(checkShifts, user.getTeamId());
			}else {
				throw new BusinessException("team.is.null");
			}
		}else {
			//全员通用打卡模式
			att = this.attendanceSettingsService.selectAttendanceSettingsByCheckShiftsAndTeamId(checkShifts, "");
		}*/
		att = this.attendanceSettingsService.selectAttendanceSettingsByCheckShiftsAndTeamId(checkShifts, "");
		if(att==null) {
			throw new BusinessException("at.is.null");
		}
		//判断打卡时间是否在范围内
		/*if(!DateUtil.isBelongHHmmss(new Date(),att.getCheckStartTime(),att.getCheckEndTime())){
			throw new BusinessException("time.is.out");
		}*/
		map.put("disparity", LocationUtils.getDistance(Double.valueOf(lat), Double.valueOf(log), Double.valueOf(att.getLat()), Double.valueOf(att.getLog())));
		map.put("distance", att.getDistance().doubleValue());
		att =null;
		return map;
	}
	/****
	 * 
	     * @方法名：insertPunchInRecord
	     * @描述： 前端打卡
	     * @作者： lijing
	     * @日期： 2019年7月11日
	 */
	public void insertPunchInRecord(PunchInRecord punchInRecord) {
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		Map<String, Object> map = judgeCheckInIsAllowed(punchInRecord.getLat(), punchInRecord.getLog(), String.valueOf(punchInRecord.getCheckShifts()), user);
		if(map == null) {
			throw new BusinessException("","不在本次考勤时间范围内！");
		}
		double disparity = (double) map.get("disparity");
		double distance = (double) map.get("distance");
		if(Math.abs(disparity) > distance) {
			throw new BusinessException("range.is.out");
		}
		//找出最大的班次
		AttendanceSettings att = null;
		//判断打卡班次
		String isDailyAttendanceCardOpened = ParamUtil.getValue("isDailyAttendanceCardOpened");
		/*if(isDailyAttendanceCardOpened !=null && "1".equals(isDailyAttendanceCardOpened)) {
			//开启班组打卡模式
			if(user.getTeamId()!=null && !"".equals(user.getTeamId())) {
				att = this.attendanceSettingsService.selectMAXcheckShifts(user.getTeamId());
			}else {
				throw new BusinessException("team.is.null");
			}
		}else {
			//全员通用打卡模式
			att = this.attendanceSettingsService.selectMAXcheckShifts("");
		}*/
		//全员通用打卡模式
		att = this.attendanceSettingsService.selectMAXcheckShifts("");
		punchInRecord.setId(UUIDUtil.getUUID());
		/*punchInRecord.setUserId(user.getUserId() == null ? user.getId():user.getUserId());*/
		punchInRecord.setCheckTime(new Date());
		this.mapper.insertSelective(punchInRecord);
		/*if(att.getCheckShifts()!=null&&String.valueOf(att.getCheckShifts()).equals(String.valueOf(punchInRecord.getCheckShifts()))) {
			//为当天最后一次打卡班次  进行打卡统计
			this.attendanceStatisticsService.insertAttendanceStatistics(user);
		}*/

	}
	
	/*************************************APP******************************************************/
	/****
	 * 
	     * @方法名：selectPunchInRecordListOnMoble
	     * @描述： 我的打卡记录
	     * @作者： lijing
	     * @日期： 2019年7月11日
	 */
	public List<PunchInRecord> selectPunchInRecordListOnMoble(String checkTime,String userId){
		
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null ) {
			throw new BusinessException("not.login");
		}
		if(userId != null && !"".equals(userId)) {
			//判断是否有权限查询
			if(user.getAssumeOffice()!=null && user.getAssumeOffice().intValue()==1) {
				List<UserTeam> usertramList = user.getUserTeamList();
		        if(usertramList==null || usertramList.size() == 0) {
		        	throw new BusinessException("team.is.null");
		        }
		        StringBuffer teamId = new StringBuffer();
		        for(UserTeam u:usertramList) {
		        	teamId.append(u.getTeamId()+",");
		        }
				boolean b = this.usersService.judgeThisUserInTeam(teamId.toString(), userId);
				if(!b) {
					throw new BusinessException("auth.is.erreo");
				}
			}
		}else {
			userId = user.getId();
		}
		if(checkTime == null) {
			checkTime = DateUtil.formatyyyyMMddHHmmss(new Date());
		}
		List<PunchInRecord> list = this.mapper.selectPunchInRecordListOnMoble(checkTime,userId);
		if (list.size() <= 0){
			throw new BusinessException("data.is.null");
		}
		return list;
	}



	/**
	　* @description: TODO   查询部门下员工的打卡记录
	　* @param [checkTime]
	　* @return java.util.List<com.liaoyin.travel.entity.attendance.PunchInRecord>
	　* @throws
	　* @author privatePanda777@163.com
	　* @date 2019/8/30 09:37
	　*/
	public List<PunchInRecord> selectTeamPunchInRecordListOnMoble(String checkTime){
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null ) {
			throw new BusinessException("not.login");
		}
		StringBuffer teamId = new StringBuffer();
		//判断是否有权限查询
		if(user.getAssumeOffice()!=null && user.getAssumeOffice().intValue()==1) {
			List<UserTeam> usertramList = user.getUserTeamList();
			if(usertramList==null || usertramList.size() == 0) {
				throw new BusinessException("team.is.null");
			}
			boolean b = this.usersService.judgeThisUserInTeam(teamId.toString(), user.getId());
			if(!b) {
				throw new BusinessException("auth.is.erreo");
			}
			for(UserTeam u:usertramList) {
				teamId.append(u.getTeamId()+",");
			}
		}
		if (null == checkTime) {
			checkTime = DateUtil.formatyyyyMMddHHmmss(new Date());
		}
		List<PunchInRecord> punchInRecords = this.mapper.selectTeamPunchInRecordListOnMoble(teamId.toString(), checkTime);
		return punchInRecords;
	}


	public List<PunchInRecord> selectTeamPunchInRecordList(String checkTime){
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null ) {
			throw new BusinessException("not.login");
		}
		StringBuffer teamId = new StringBuffer();
		//判断是否有权限查询
		if(user.getAssumeOffice()!=null && user.getAssumeOffice().intValue()==1) {
			List<UserTeam> usertramList = user.getUserTeamList();
			if(usertramList==null || usertramList.size() == 0) {
				throw new BusinessException("team.is.null");
			}
			boolean b = this.usersService.judgeThisUserInTeam(teamId.toString(), user.getId());
			if(!b) {
				throw new BusinessException("auth.is.erreo");
			}
			for(UserTeam u:usertramList) {
				teamId.append(u.getTeamId()+",");
			}
		}
		if (null == checkTime) {
			checkTime = DateUtil.formatyyyyMMddHHmmss(new Date());
		}
		List<PunchInRecord> punchInRecords = this.mapper.selectTeamPunchInRecordList(teamId.toString(), checkTime);
		return punchInRecords;
	}

	/**
	 * @方法名：selectPunchInRecordListOnBack
	 * @描述： 查询指定用户的考勤记录
	 * @作者： lijing
	 * @日期： Created in 2019/8/15 20:31
	 */
	public List<PunchInRecord> selectPunchInRecordListOnBack(String startTime,String endTime,Integer num,Integer size,String userId){
		UserInfo userInfo = PartyUtil.getCurrentUserInfo();
		if(userInfo.getId() != null && !"".equals(userInfo.getId())) {
			//判断是否有权限查询
			if(userInfo.getAssumeOffice()!=null && userInfo.getAssumeOffice().intValue()==1) {
				List<UserTeam> usertramList = userInfo.getUserTeamList();
		        if(usertramList==null || usertramList.size() == 0) {
		        	throw new BusinessException("team.is.null");
		        }
		        StringBuffer teamId = new StringBuffer();
		        for(UserTeam u:usertramList) {
		        	teamId.append(u.getTeamId()+",");
		        }
				boolean b = this.usersService.judgeThisUserInTeam(teamId.toString(), userInfo.getId());
				if(!b) {
					throw new BusinessException("auth.is.erreo");
				}
			}
		}
		PageHelper.startPage(num,size);
		List<PunchInRecord> list = this.mapper.selectPunchInRecordListOnBack(startTime+" 00:00:00",endTime+" 23:59:59",userId);
		return list;
	}
}
